package com.zllkj.mm.module.general.fragments;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.zllkj.mm.AppManager;
import com.zllkj.mm.R;
import com.zllkj.mm.api.network.RetrofitHelper;
import com.zllkj.mm.api.network.RxHelper;
import com.zllkj.mm.api.network.subscriber.BaseRxSubscriber;
import com.zllkj.mm.api.network.subscriber.BaseString;
import com.zllkj.mm.base.BaseAppFragment;
import com.zllkj.mm.common.L;
import com.zllkj.mm.helper.InputTextHelper;
import com.zllkj.mm.model.entity.LoginVo;
import com.zllkj.mm.module.UIHelper;
import com.zllkj.mm.module.home.fragments.EditInfoFragment;
import com.zllkj.mm.module.home.fragments.SetPwdFragment;
import com.zllkj.mm.module.main.MainActivity;
import com.zllkj.mm.module.main.fragments.MineFragment;
import com.zllkj.mm.util.KLog;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import androidx.core.app.ActivityCompat;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;


public class LoginFragment2 extends BaseAppFragment {

    public static LoginVo loginS;
    boolean confirmEnable =true;
    public static String deviceId;
    long timeDenied;//测试结果不再询问拒绝8次/s
    private Disposable codeDisposable;

    @BindView(R.id.rlCode)
    RelativeLayout rlCode;
    @BindView(R.id.etPhone)
    EditText etPhone;
    @BindView(R.id.etPwd)
    EditText etPwd;
    @BindView(R.id.etCode)
    EditText etCode;
    @BindView(R.id.forget)
    TextView forget;
    @BindView(R.id.accountLogin)
    TextView accountLogin;
    @BindView(R.id.getCode)
    TextView getCode;
    @BindView(R.id.codeLogin)
    TextView codeLogin;
    @BindView(R.id.confirm)
    TextView confirm;
    @BindView(R.id.wechatLogin)
    ImageView wechatLogin;
    @BindView(R.id.qqLogin)
    ImageView qqLogin;
    @BindView(R.id.register)
    TextView register;
    @BindView(R.id.v_main)
    View v_main;
    @BindView(R.id.tvP)
    View tvP;
    @BindView(R.id.llLogin)
    LinearLayout llLogin;
    @BindView(R.id.tvRegister)
    TextView tvRegister;
    @BindView(R.id.llLoginLine)
    LinearLayout llLoginLine;
    @BindView(R.id.privacyPolicy)
    TextView privacyPolicy;
    @BindView(R.id.agreement)
    TextView agreement;
    @BindView(R.id.t1)
    ImageView t1;
    @BindView(R.id.back)
    View back;
    @BindView(R.id.rlPwd)
    View rlPwd;

    public static LoginFragment2 newInstance() {
        LoginFragment2 fragment = new LoginFragment2();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_login2;
    }

    private int mode = 2;//1密码登录 2验证码登录 3注册
    InputTextHelper inputTextHelper;
    boolean agree = true;

    @Override
    protected void initView(View rootView) {
        super.initView(rootView);
//      back.setVisibility(AppManager.getAppManager().activityStack.size() > 1 ? View.VISIBLE : View.GONE);//ll返回按钮改游客模式
//      ((BaseCommonActivity) getActivity()).top_top_bg_Gone();
//      register.setText(Html.fromHtml("还没有账号？<font color='#4099f7'>马上注册</font>"));
        etPhone.setText("");
        etPwd.setText("");
//        inputTextHelper = InputTextHelper.with(getActivity())
//                .addView(etPhone)
//                .addView(etCode)
//                .setMain(confirm)
//                .setListener(helper -> etPhone.getText().toString().length() == 11
//                                && (
//                                ((mode == 1 && etPwd.getText().toString().length() >= 1) && etCode.getText().toString().length() == 0)
//                                        || ((mode > 1 && etCode.getText().toString().length() == 4) && etPwd.getText().toString().length() == 0)
//                        )
//                )
//                .build();

        tvRegister.setVisibility(View.GONE);
        rlPwd.setVisibility(View.GONE);
        forget.setVisibility(View.GONE);

        //读写权限
        ActivityCompat.requestPermissions(getActivity(), new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE
//                , android.Manifest.permission.ACCESS_FINE_LOCATION
//                , android.Manifest.permission.ACCESS_COARSE_LOCATION
        }, 1);
//        requestPermissions();
        MineFragment.userInfo = null;
//        getIMEI(getContext());
        //用于测试编辑信息
      //  addFragment(EditInfoFragment.newInstance());
    }

    @OnClick({R.id.t1, R.id.back,  R.id.forget, R.id.confirm, R.id.accountLogin, R.id.codeLogin, R.id.getCode, R.id.qqLogin, R.id.wechatLogin, R.id.register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                if (AppManager.getAppManager().activityStack.size() > 1) {
                    removeFragment();
                } else {
                    startActivity(new Intent(getContext(), /*EmptyUtils.isEmpty(Hawk.get(L.token)) ?
                                LoginActivity.class : */MainActivity.class)
                            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
                }
                break;
            case R.id.t1:
                agree = !agree;
                t1.setImageResource(agree ? R.mipmap.mm_select_y : R.mipmap.mm_select_n);
                break;
            case R.id.codeLogin:
//                if (mode == 2) return;
                mode = 2;
                getCode.setVisibility(View.VISIBLE);
                rlPwd.setVisibility(View.GONE);
                rlCode.setVisibility(View.VISIBLE);
                forget.setVisibility(View.GONE);
                codeLogin.setTextColor(getResources().getColor(R.color.baseAppColor));
                accountLogin.setTextColor(getResources().getColor(R.color.gray_ccc));
                ObjectAnimator objectAnimator1 = ObjectAnimator.ofFloat(tvP, "translationX", tvP.getWidth(), 0);
                objectAnimator1.setDuration(200);
                objectAnimator1.start();
                break;
            case R.id.accountLogin:
                if (mode == 1) return;
                mode = 1;
                getCode.setVisibility(View.GONE);
                rlPwd.setVisibility(View.VISIBLE);
                rlCode.setVisibility(View.GONE);
                //forget.setVisibility(View.VISIBLE);//L.mm
                codeLogin.setTextColor(getResources().getColor(R.color.gray_ccc));
                accountLogin.setTextColor(getResources().getColor(R.color.baseAppColor));
                ObjectAnimator objectAnimator2 = ObjectAnimator.ofFloat(tvP, "translationX", 0, tvP.getWidth());
                objectAnimator2.setDuration(200);
                objectAnimator2.start();
                break;
            case R.id.register:
//                addFragment(RegisterOrForgetFragment.newInstance("注册"));
                //1密码登录 2验证码登录 3注册
                if (mode != 3) {
                    mode = 3;

                } else {
                    mode = 2;
                }
                confirm.setText(mode == 3 ? "注册" : "登录");
                register.setText(mode == 3 ? "已有账号？去登录" : "新用户注册");
                getCode.setVisibility(mode == 3 ? View.VISIBLE : View.GONE);
                rlPwd.setVisibility(mode == 3 ? View.GONE : View.VISIBLE);
                rlCode.setVisibility(mode == 3 ? View.VISIBLE : View.GONE);
                forget.setVisibility(mode == 3 ? View.GONE : View.VISIBLE);
                tvRegister.setVisibility(mode == 3 ? View.VISIBLE : View.GONE);
                llLogin.setVisibility(mode == 3 ? View.GONE : View.VISIBLE);
                llLoginLine.setVisibility(mode == 3 ? View.GONE : View.VISIBLE);
                if (mode == 2) onViewClicked(codeLogin);
                break;
        }
        if (!agree) {
            L.showToast("请阅读并勾选用户与隐私协议");
            return;
        }
        switch (view.getId()) {
            case R.id.getCode:
                if (!L.phoneRegex(etPhone.getText().toString())) {
                    L.showToast("请输入正确的手机号码");
                    return;
                }
                RetrofitHelper.getInstance().getApi()
                                .getTelCode(new HashMap() {{
                                    put("phone", etPhone.getText().toString());
                                    put("smsType", mode == 3 ? 1 : 2);//1-注册、2-登录、3-找回密码、4-手机号码验证、5-绑定新手机号码
                                }})
                                .compose(RxHelper.defaultHandleResult())
                                .subscribe(new BaseRxSubscriber<BaseString>() {
                                    @Override
                                    protected void onSucc(BaseString baseString) {
                                        L.showToast("发送成功");
                                        getCode.setEnabled(false);
//                                getCode.setBackground(getResources().getDrawable(R.drawable.solidbb_radius5));
                                        codeDisposable = Flowable.interval(0, 1, TimeUnit.SECONDS)
                                                .take(60)
                                                .observeOn(AndroidSchedulers.mainThread())
                                                .subscribe(aLong -> {
                                                    getCode.setText("（" + (60 - aLong) + "秒）");
                                                    if (aLong + 1 == 60) {
                                                        getCode.setText("获取");
                                                        getCode.setEnabled(true);
//                                                    getCode.setBackground(getResources().getDrawable(R.drawable.btn_pass_up_blue));
                                                    }
                                                });
                                    }
                                })
                ;
                break;
            case R.id.confirm:
                if (!confirmEnable) {
                    return;
                }
                if (!L.phoneRegex(etPhone.getText().toString())) {
                    L.showToast("请输入正确的手机号码");
                    return;
                }
                //1密码登录 2验证码登录 3注册
                if (mode == 1) {
                    RetrofitHelper.getInstance().getApi()
                            .login_pwd(new HashMap() {{
                                put("phone", etPhone.getText().toString());
                                put("password", etPwd.getText().toString());
                            }})
                            .compose(RxHelper.<LoginVo>defaultHandleResult())
                            .subscribe(new BaseRxSubscriber<LoginVo>() {
                                @Override
                                protected void onSucc(LoginVo o) {
                                    Hawk.put(L.iM_userId, o.userId);
                                    Hawk.put(L.token, o.token);
                                    Hawk.put(L.imToken, o.imToken);
                                    L.showToast("登录成功");
                                    if (1==o.ifPerfectSelfInfo){
                                        UIHelper.showMainPage(getActivity());
                                    }else {
                                        addFragment(EditInfoFragment.newInstance());
                                    }

                                }
                            })
                    ;
                   // return;
                }
                if (mode == 2) {
                    RetrofitHelper.getInstance().getApi()
                            .loginByCode(new HashMap() {{
                                put("phone", etPhone.getText().toString());
                                put("verifyCode", etCode.getText().toString());
                            }})
                            .compose(RxHelper.<LoginVo>defaultHandleResult())
                            .subscribe(new BaseRxSubscriber<LoginVo>() {
                                @Override
                                protected void onSucc(LoginVo o) {
                                    loginS = o;
                                  //  loginS.phone = etPhone.getText().toString();
                                    if (1==o.alreadyPassword) {
                                        Hawk.put(L.iM_userId, o.userId);
                                        Hawk.put(L.token, o.token);
                                        Hawk.put(L.imToken, o.imToken);
                                        L.showToast("登录成功");
                                        UIHelper.showMainPage(getActivity());
                                    } else {
                                        addFragment(SetPwdFragment.newInstance());
                                    }
                                }
                            });
                  //  return;
                }
                if (mode == 3) {
                    RetrofitHelper.getInstance().getApi()
                            .registerByPhone(new HashMap() {{
                                put("phone", etPhone.getText().toString());
                                put("verifyCode", etCode.getText().toString());
                            }})
                            .compose(RxHelper.<LoginVo>defaultHandleResult())
                            .subscribe(new BaseRxSubscriber<LoginVo>() {
                                @Override
                                protected void onSucc(LoginVo o) {
                                    loginS = o;
                                 //   LoginVo.phone = etPhone.getText().toString();
                                    if (1==o.alreadyPassword) {
                                        Hawk.put(L.iM_userId, o.userId);
                                        Hawk.put(L.token, o.token);
                                        Hawk.put(L.imToken, o.imToken);
                                        L.showToast("注册成功");
                                        UIHelper.showMainPage(getActivity());
                                    } else {
                                        addFragment(SetPwdFragment.newInstance());
                                    }
                                }
                            })
                    ;
                   // return;
                }
                break;
            case R.id.qqLogin:
                L.showToast("待续.");
                break;
            case R.id.wechatLogin:
                L.showToast("待续.");
                break;
        }
    }

    @SuppressLint("MissingPermission")
    public static String getIMEI(Context context) {
        TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        try {
            Method method = manager.getClass().getMethod("getImei", int.class);
            String imei1 = (String) method.invoke(manager, 0);
            String imei2 = (String) method.invoke(manager, 1);
            KLog.e(imei1);
            KLog.e(imei2);
            if (TextUtils.isEmpty(imei2)) {
                return imei1;
            }
            if (!TextUtils.isEmpty(imei1)) {
                //因为手机卡插在不同位置，获取到的imei1和imei2值会交换，所以取它们的最小值,保证拿到的imei都是同一个
                String imei = "";
                if (imei1.compareTo(imei2) <= 0) {
                    imei = imei1;
                } else {
                    imei = imei2;
                }
                return imei;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return manager.getDeviceId();
        }
        return "";
    }

}
